package com.jdy.singleton;

import com.jdy.singleton.serializable.SerializableSingleton;

import java.io.*;

/**
 * 常用工具包
 * <p>
 * [Description]
 * <p>
 * 创建人 Dale 时间 2019/10/18 20:34
 */
public class SerializableTest {

    public static void main(String[] args) {
        /**
         * 序列化破坏单例模式
         */
        FileOutputStream fileOutputStream = null;
        SerializableSingleton instance = SerializableSingleton.getInstance();
        try {
            //保存对象
            fileOutputStream = new FileOutputStream("SerializableSingleton.obj");
            ObjectOutputStream outputStream = new ObjectOutputStream(fileOutputStream);
            outputStream.writeObject(instance);
            outputStream.flush();
            outputStream.close();

            //反序列化
            FileInputStream fileInputStream = new FileInputStream("SerializableSingleton.obj");
            ObjectInputStream inputStream = new ObjectInputStream(fileInputStream);
            Object object = inputStream.readObject();//内部还是会用到反射
            fileInputStream.close();
            inputStream.close();
            System.out.println("反射调用单例 ： " + object + ",   正常使用单例 ： " + instance);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (fileOutputStream != null) {
                try {
                    fileOutputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
